<template>
    <view v-if="data">
        <view
            style="
                display: flex;
                flex-direction: column;
                height: 100vh;
                justify-content: space-between;
            "
        >
            <view style="flex: 1; overflow: scroll; background-color: #eee">
                <u-form
                    style="margin-bottom: 10px"
                    v-if="curCus.bmn == '1' || curCus.bsjmn == '1'"
                    class="form bg-white"
                    :model="model"
                    ref="uForm"
                    label-position="left"
                >
                    <u-form-item
                        label="核发店面:"
                        prop="testCarVen"
                        label-width="200"
                        :label-style="{ 'font-weight': 'bold' }"
                    >
                        <js-select
                            :childName="'None'"
                            v-model="model.code"
                            :showFilter="true"
                            :items="selectList"
                            placeholder="请选择核发店面"
                            :tree="false"
                            :label-value="model.name"
                            @label-input="model.name = $event"
                            @confirm="selectConfirm"
                        >
                        </js-select>
                        <!-- @confirm="selectConfirm" -->
                    </u-form-item>
                </u-form>
                <u-cell-group>
                    <!-- <u-cell-item  :title="'核发店面'" ></u-cell-item> -->
                    <u-cell-item
                        icon="map"
                        :use-label-slot="true"
                        @click="xzAddress"
                    >
                        <template #title>
                            <view class="">
                                {{ addressData.cdeliverunit || "" }}
                                {{ addressData.cenglishadd4 || "" }}
                            </view>
                        </template>
                        <template #label>
                            <view class="">{{
                                addressData.cdeliveradd ||
                                "请先完善收货地址信息"
                            }}</view>
                        </template>
                    </u-cell-item>
                </u-cell-group>

                <view
                    style="
                        margin-top: 10px;
                        background-color: #fff;
                        padding: 10px;
                    "
                >
                    <u-section
                        title="商品清单"
                        :right="false"
                        line-color="#00aa00"
                        font-size="32"
                    ></u-section>

                    <view
                        style="
                            padding: 10px;
                            border-top: 1px solid #eee;
                            margin-top: 10px;
                        "
                    >
                        <view v-for="(item, index) in list" :key="index">
                            <view
                                v-if="item.busType == '0'"
                                style="
                                    display: flex;
                                    margin: 10px 0;
                                    border-bottom: 1px solid #eee;
                                "
                            >
                                <image
                                    class="item-menu-image"
                                    mode="aspectFit"
                                    :src="
                                        item.shopInv.basInv.picUrl
                                            ? vuex_config.baseUrl +
                                              item.shopInv.basInv.picUrl
                                            : ''
                                    "
                                >
                                </image>
                                <view style="margin-left: 10px; flex: 1">
                                    <view
                                        style="
                                            font-weight: bold;
                                            font-size: 16px;
                                            margin-bottom: 10px;
                                        "
                                    >
                                        {{ item.shopInv.basInv.cinvname }}
                                    </view>
                                    <view>
                                        <view style="color: #aaa">
                                            规格：{{
                                                item.shopInv.basInv.cinvstd
                                                    ? item.shopInv.basInv
                                                          .cinvstd
                                                    : ""
                                            }}</view
                                        >
                                        <!-- <view style="background:  bisque ;padding: 5px;color: #ff874b;border-radius: 5px">1件起订</view> -->
                                    </view>
                                    <view
                                        style="
                                            display: flex;
                                            justify-content: space-between;
                                            margin-top: 10px;
                                        "
                                    >
                                        <view>
                                            <text
                                                style="
                                                    color: red;
                                                    font-size: 20px;
                                                "
                                                >￥{{
                                                    item.shopInv.basInv.appPrice
                                                        ? item.shopInv.basInv
                                                              .appPrice
                                                        : "暂无单价"
                                                }}</text
                                            >
                                            <text
                                                >/{{
                                                    item.shopInv.basInv
                                                        .appUnitName
                                                }}</text
                                            >
                                        </view>
                                        <view>x {{ item.iqty }}</view>
                                    </view>
                                </view>
                            </view>
                            <view
                                v-if="item.busType == '1'"
                                style="
                                    display: flex;
                                    margin: 10px 0;
                                    border-bottom: 1px solid #eee;
                                "
                            >
                                <image
                                    class="item-menu-image"
                                    mode="aspectFit"
                                    :src="
                                        item.shopProductSell.picUrl
                                            ? vuex_config.baseUrl +
                                              item.shopProductSell.picUrl
                                            : ''
                                    "
                                >
                                </image>
                                <view style="margin-left: 10px; flex: 1">
                                    <view
                                        style="
                                            font-weight: bold;
                                            font-size: 16px;
                                            margin-bottom: 10px;
                                        "
                                    >
                                        {{ item.shopProductSell.abbName }}
                                    </view>
                                    <view>
                                        <view style="color: #aaa">
                                            简介：{{
                                                item.shopProductSell.ctitle
                                                    ? item.shopProductSell
                                                          .ctitle
                                                    : ""
                                            }}</view
                                        >
                                        <!-- <view style="background:  bisque ;padding: 5px;color: #ff874b;border-radius: 5px">1件起订</view> -->
                                    </view>
                                    <view
                                        style="
                                            display: flex;
                                            justify-content: space-between;
                                            margin-top: 10px;
                                        "
                                    >
                                        <view>
                                            <text
                                                style="
                                                    color: red;
                                                    font-size: 20px;
                                                "
                                                >￥{{
                                                    item.shopProductSell.fprice
                                                        ? item.shopProductSell
                                                              .fprice
                                                        : "暂无单价"
                                                }}</text
                                            >
                                            <!-- <text>/{{item.shopProductSell.basInv.appUnitName}}</text> -->
                                            <text
                                                >/{{
                                                    item.shopProductSell
                                                        .unitName
                                                }}</text
                                            >
                                        </view>
                                        <view>x {{ item.iqty }}</view>
                                    </view>
                                </view>
                            </view>
                            <!-- 商品清单详情组件 -->
                            <product-list-detail
                                v-if="item.busType == '3'"
                                :visible="
                                    expandedPackages[item.shopSalesPackage.id]
                                "
                                :package-data="
                                    packageDetails[item.shopSalesPackage.id]
                                "
                                :base-url="vuex_config.baseUrl"
                                @product-click="onProductClick"
                                @quantity-change="onQuantityChange"
                                @item-select="onItemSelect"
                            />
                            <view
                                v-if="item.busType == '3'"
                                style="
                                    display: flex;
                                    margin: 10px 0;
                                    border-bottom: 1px solid #eee;
                                "
                            >
                                <image
                                    class="item-menu-image"
                                    mode="aspectFit"
                                    :src="
                                        item.shopSalesPackage.picUrl
                                            ? vuex_config.baseUrl +
                                              item.shopSalesPackage.picUrl
                                            : ''
                                    "
                                >
                                </image>
                                <view style="margin-left: 10px; flex: 1">
                                    <view
                                        style="
                                            font-weight: bold;
                                            font-size: 16px;
                                            margin-bottom: 10px;
                                        "
                                    >
                                        {{ item.shopSalesPackage.title }}
                                    </view>
                                    <view
                                        class="flex justify-between align-center"
                                    >
                                        <view style="color: #aaa">{{
                                            item.shopSalesPackage.batchType == 1
                                                ? "首批"
                                                : "非首批"
                                        }}</view>
                                        <view
                                            style="
                                                background: bisque;
                                                padding: 5px;
                                                color: #ff874b;
                                                border-radius: 5px;
                                            "
                                            @click="
                                                toggleDetails(
                                                    item.shopSalesPackage,
                                                    index
                                                )
                                            "
                                        >
                                            {{
                                                expandedPackages[
                                                    item.shopSalesPackage.id
                                                ]
                                                    ? "关闭"
                                                    : "展开"
                                            }}
                                        </view>
                                    </view>
                                    <view
                                        style="
                                            display: flex;
                                            justify-content: space-between;
                                            margin-top: 10px;
                                        "
                                    >
                                        <view>
                                            <text
                                                style="
                                                    color: red;
                                                    font-size: 20px;
                                                "
                                                >￥{{
                                                    item.shopSalesPackage
                                                        .appPrice
                                                        ? item.shopSalesPackage
                                                              .appPrice
                                                        : "暂无单价"
                                                }}</text
                                            >
                                            <text
                                                >/{{
                                                    item.shopSalesPackage
                                                        .unitName
                                                }}</text
                                            >
                                        </view>
                                        <view>x {{ item.iqty }}</view>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- <view style="display: flex;margin: 10px 0;">
						<image class="item-menu-image" :src="'https://cdn.uviewui.com/uview/common/classify/1/2.jpg'" mode=""></image>
						<view style="margin-left: 10px;">
							<view style="font-weight: bold;font-size: 16px;margin-bottom: 10px;">蒙牛悠瑞富硒高钙羊奶粉800gX6罐蒙牛悠牛悠</view>
							<view >
								<view style="color: #aaa;">规格:800g*6</view>
							</view>
							<view style="display: flex;justify-content: space-between;margin-top: 10px;">
								<view>
									<text style="color: red;font-size: 20px;">￥990.00</text>
									<text>/件</text>
								</view>
								<view>x 2</view>
							</view>
						</view>
					</view> -->
                    </view>
                </view>

                <view
                    style="
                        margin-top: 10px;
                        background-color: #fff;
                        padding: 10px;
                    "
                >
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>优惠金额</text>
                        <text>￥{{ data.disMoney }}</text>
                    </view>
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>商品总价</text>
                        <text style="color: red">￥{{ data.sumMoney }}</text>
                    </view>
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>经销商账户余额</text>
                        <text
                            :style="{
                                color:
                                    data.cusMoney.appZhMoney < 0
                                        ? 'red'
                                        : '#000',
                            }"
                            >￥{{ data.cusMoney.appZhMoney }}</text
                        >
                    </view>
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>经销商返利余额</text>
                        <text>￥{{ data.cusMoney.appFlMoney }}</text>
                    </view>
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>经销商促销余额</text>
                        <text>￥{{ data.cusMoney.appCxMoney }}</text>
                    </view>
                    <view
                        style="
                            display: flex;
                            justify-content: space-between;
                            margin-bottom: 5px;
                        "
                    >
                        <text>信用额度</text>
                        <text>￥{{ data.cusMoney.xyMoney }}</text>
                    </view>
                </view>

                <view
                    style="
                        margin: 10px 0;
                        background-color: #fff;
                        padding: 10px;
                    "
                    v-if="vuex_basCus.batchType != '1'"
                >
                    <view style="display: flex; justify-content: space-between">
                        <u-section
                            title="促销返利使用"
                            :right="false"
                            line-color="#00aa00"
                            font-size="32"
                        ></u-section>
                        <view style="color: red; text-align: right">
                            <view class="">
                                促销返利金额最高使用上限:
                                {{ data.sumMoneyLmit }}
                            </view>
                        </view>
                    </view>
                    <view
                        style="
                            padding: 10px;
                            border-top: 1px solid #eee;
                            margin-top: 10px;
                            margin-right: 10px;
                        "
                    >
                        <!-- 经销商返利余额选项 -->
                        <view
                            style="
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                margin-bottom: 15px;
                            "
                        >
                            <view style="display: flex; align-items: center">
                                <radio
                                    :checked="promotionType === 1"
                                    @click="promotionType = 1"
                                    color="#ff6600"
                                    style="margin-right: 10px"
                                />
                                <view>经销商返利余额</view>
                            </view>
                            <view style="display: flex; align-items: center">
                                <view style="margin-right: 10px"
                                    >￥{{
                                        promotionType === 1
                                            ? cusMoney.flhxMoney
                                            : "0.00"
                                    }}</view
                                >
                                <view v-if="promotionType === 1"
                                    ><u-icon
                                        name="edit-pen"
                                        :size="50"
                                        @click="modify(1)"
                                    ></u-icon
                                ></view>
                            </view>
                        </view>

                        <!-- 经销商促销余额选项 -->
                        <view
                            style="
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                margin-bottom: 15px;
                            "
                        >
                            <view style="display: flex; align-items: center">
                                <radio
                                    :checked="promotionType === 2"
                                    @click="promotionType = 2"
                                    color="#ff6600"
                                    style="margin-right: 10px"
                                />
                                <view>经销商促销余额</view>
                            </view>
                            <view style="display: flex; align-items: center">
                                <view style="margin-right: 10px"
                                    >￥{{
                                        promotionType === 2
                                            ? cusMoney.cxhxMoney
                                            : "0.00"
                                    }}</view
                                >
                                <view v-if="promotionType === 2"
                                    ><u-icon
                                        name="edit-pen"
                                        :size="50"
                                        @click="modifyAllocation(2)"
                                    ></u-icon
                                ></view>
                            </view>
                        </view>

                        <!-- 红色备注 -->
                        <view
                            style="
                                color: red;
                                font-size: 14px;
                                margin-bottom: 15px;
                            "
                        >
                            注：促销费用不计算业绩金额
                        </view>

                        <view>
                            备注
                            <!-- <u-input v-model="textarea" placeholder="" type="textarea" :auto-height="flase" height="50" maxlength="256" /> -->
                            <textarea
                                v-model="remarks"
                                type="text"
                                placeholder-class="line"
                                placeholder="请输入备注信息"
                                auto-height
                            />
                        </view>
                    </view>
                </view>
            </view>

            <view
                style="
                    padding: 20px;
                    display: flex;
                    justify-content: space-between;
                    border-top: 1px solid #eee;
                    background-color: #fff;
                "
            >
                <view class="flex" style="flex-direction: column">
                    <text style="font-size: 12px">需转款金额</text>
                    <text style="color: red; font-size: 16px">
                        <!-- ￥{{payMoney}} -->
                        <!-- ￥{{data.sumMoney}} -->
                        ￥{{ dkMoney }}
                    </text>
                </view>
                <view>
                    合计:
                    <text style="color: red; font-size: 20px">
                        <!-- ￥{{payMoney}} -->
                        <!-- ￥{{data.sumMoney}} -->
                        ￥{{ data.payMoney }}
                    </text>
                </view>

                <text
                    @click="submit"
                    style="
                        padding: 10px 25px;
                        background: #00aa00;
                        color: #fff;
                        border-radius: 5px;
                    "
                    >提交订单</text
                >
            </view>

            <u-modal
                v-model="numShow"
                :mask-close-able="true"
                :show-cancel-button="true"
                :show-title="false"
                @confirm="confirm"
            >
                <view style="text-align: center; padding: 20px 30px 10px">
                    <view style="margin-bottom: 10px">
                        {{ flag == "1" ? `返利金额修改` : `促销金额修改` }}
                    </view>
                    <!-- <u-number-box v-model="value" :input-width="200" :positive-integer="false"
					:nodes="content"></u-number-box> -->
                    <u-input
                        v-model="value"
                        type="digit"
                        placeholder="0.00"
                        :focus="focus"
                        :border="true"
                        @input="replaceInput"
                        clearable
                    />
                    <view
                        style="
                            color: red;
                            text-align: left;
                            font-size: 14px;
                            margin-top: 10px;
                        "
                    >
                        <text>
                            {{
                                flag == "1"
                                    ? `返利金额上限：`
                                    : `促销金额上限：`
                            }}</text
                        >
                        <text style="font-size: 16px"
                            >￥{{
                                flag == "1"
                                    ? data.flMoneyLmit
                                    : data.cxMoneyLmit
                            }}</text
                        >
                    </view>
                </view>
            </u-modal>
        </view>

        <!-- 赠品选择弹窗 -->
        <gift-selection
            :show.sync="showGiftModal"
            :cus-code="cusCode"
            :pay-money="giftAvailableMoney"
            @cancel="onGiftCancel"
            @confirm="onGiftConfirm"
        />
        <!-- 分配比例弹框 -->
        <allocation-ratio
            v-if="showAllocationModal"
            :show.sync="showAllocationModal"
            :findInvExcDataList="list"
            @cancel="showAllocationModal = false"
            @confirm="onRatioConfirm"
        />
    </view>
</template>

<script>
import util from "@/common/fire.js";
import ProductListDetail from "./product-list-detail.vue";
import GiftSelection from "./gift-selection.vue";
import AllocationRatio from "./allocation-ratio.vue";

export default {
    components: {
        ProductListDetail,
        GiftSelection,
        AllocationRatio,
    },

    data() {
        return {
            addressData: {},
            focus: false,
            remarks: "",
            value: 0,
            list: [],
            payMoney: 0,
            show: false,
            numShow: false,
            title: "选择收货地址",
            curCus: {},
            data: "",
            cusMoney: {
                flhxMoney: "0.00",
                cxhxMoney: "0.00",
            },
            flag: "",
            model: {},
            selectList: [],
            // 展开状态管理
            expandedPackages: {},
            // 套餐包详情数据
            packageDetails: {},
            // 赠品弹窗相关
            showGiftModal: false,
            cusCode: "",
            // 促销返利选择类型：1-经销商返利余额，2-经销商促销余额
            promotionType: 1,
            payGiftMoney: 0,

            // 分配比例弹框相关
            showAllocationModal: false,
            findInvExcDataList: [],
            isRatio: false,
        };
    },
    computed: {
        // 计算赠品可用金额：直接使用已计算的payMoney（实际需要支付的金额）
        giftAvailableMoney() {
            // payMoney已经是：商品总价 - 返利金额 - 促销金额 - 优惠金额
            const availableMoney = Number(this.payMoney) || 0;

            return Math.max(0, availableMoney);
        },
        dkMoney() {
            console.log(this.payMoney, this.data?.cusMoney?.appZhMoney);
            const dkMoneys = this.payMoney - this.data?.cusMoney?.appZhMoney;
            return dkMoneys > 0 ? dkMoneys : 0;
        },
    },
    onLoad(params) {
        uni.$on("xzaddressData", (data) => {
            this.addressData = data;
        });
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on("acceptData", function (data) {
            console.log("acceptData", data);
            that.data = data;

            that.data.cusMoney.xyMoney = util.toFixed2(data.cusMoney.xyMoney);

            that.data.disMoney = util.toFixed2(data.disMoney);
            that.data.sumMoney = util.toFixed2(data.sumMoney);

            that.data.flMoneyLmit = util.toFixed2(data.flMoneyLmit);
            that.data.cxMoneyLmit = util.toFixed2(data.cxMoneyLmit);

            that.data.payMoney = util.toFixed2(data.payMoney);
            // that.data.zhMoney=util.toFixed2(data.zhMoney)
            // that.data.flMoney=util.toFixed2(data.flMoney)
            // that.data.cxMoney=util.toFixed2(data.cxMoney)
            // that.cusMoney = {...that.data.cusMoney}
            // that.cusMoney.flhxMoney=util.toFixed2(that.cusMoney.flhxMoney)
            // that.cusMoney.cxhxMoney=util.toFixed2(that.cusMoney.cxhxMoney)

            that.data.sumMoneyLmit = util.toFixed2(data.sumMoneyLmit);

            that.data.cusMoney.appZhMoney = util.toFixed2(
                data.cusMoney.appZhMoney
            );
            that.data.cusMoney.appFlMoney = util.toFixed2(
                data.cusMoney.appFlMoney
            );
            that.data.cusMoney.appCxMoney = util.toFixed2(
                data.cusMoney.appCxMoney
            );

            that.list = that.data.carList.map((item) => {
                if (item.busType == "0") {
                    item.shopInv.basInv.appPrice = util.toFixed2(
                        item.shopInv.basInv.appPrice
                    );
                    item.cinvcode = item.shopInv.basInv.cinvcode; //ratio
                    item.ratio = 0;
                } else if (item.busType == "3") {
                    item.shopSalesPackage.appPrice = util.toFixed2(
                        item.shopSalesPackage.fmaount
                    );
                    console.log("appPrice===", item.shopSalesPackage.appPrice);
                    item.shopSalesPackage.unitName = "套";

                    item.salesRefList.forEach((it) => {
                        it.cinvcode = it.basInv.cinvcode;
                        it.ratio = 0;
                    });
                } else {
                    item.shopProductSell.fprice = util.toFixed2(
                        item.shopProductSell.fprice
                    );
                    if (item.busType == "1") {
                        item.cinvcode = item.shopProductSell.basInv.cinvcode;
                        item.ratio = 0;
                    }
                }
                return item;
            });
            that.payMoney = util.toFixed2(that.data.payMoney);

            // 优先级存货：
            that.$u.api.shop
                .findInvExcData({ ccuscode: that.vuex_basCus.code })
                .then((res) => {
                    console.log(res, "------------------");
                    if (res.length) {
                        that.findInvExcDataList = res.map((item) => {
                            return item.cinvcode;
                        });
                        console.log(
                            that.findInvExcDataList,
                            "that.findInvExcDataList"
                        );

                        that.list.forEach((item) => {
                            if (item.busType == "0" || item.busType == "1") {
                                if (
                                    that.findInvExcDataList.includes(
                                        item.cinvcode
                                    )
                                ) {
                                    that.isRatio = true;
                                    item.isRatio = true;
                                }
                            }
                            // 套餐包
                            if (item.busType == "3") {
                                item.salesRefList.forEach((it) => {
                                    if (
                                        that.findInvExcDataList.includes(
                                            it.invCode
                                        )
                                    ) {
                                        that.isRatio = true;
                                        it.isRatio = true;
                                    }
                                });
                            }
                        });
                    }
                });
        });
        // console.log(params,'params=======');
        // this.data = JSON.parse(params.list)
        // this.cusMoney = this.data.cusMoney
        // this.list = this.data.carList
        // this.payMoney = this.data.payMoney

        this.$u.api.shop.findMnCusListData().then((res1) => {
            this.selectList = res1.map((item) => {
                item.value = item.code;
                item.name = item.cusDefine1
                    ? `${item.name}/ ${item.cusDefine1}`
                    : item.name;
                return item;
            });
        });
        this.$u.api.shop.getCurCus().then((res) => {
            this.curCus = {
                bmn: res.bmn,
                bsjmn: res.bsjmn,
                batchType: res?.cusExp?.batchType || "",
                batchPages: res?.cusExp?.batchPages || "",
            };
        });

        this.$u.api.shop
            .addressListData({ ccuscode: this.vuex_basCus.code })
            .then((res) => {
                if (res.list.length) {
                    this.addressData = res.list[0];
                }
            });
    },
    watch: {
        // 监听促销类型变化，重置未选中的金额
        promotionType(newVal, oldVal) {
            if (newVal !== oldVal) {
                if (newVal === 1) {
                    // 选择返利余额，重置促销余额
                    this.cusMoney.cxhxMoney = "0.00";
                } else if (newVal === 2) {
                    // 选择促销余额，重置返利余额
                    this.cusMoney.flhxMoney = "0.00";
                }
                // 重新计算支付金额
                this.calculatePayMoney();
            }
        },
    },
    methods: {
        // 计算支付金额
        calculatePayMoney() {
            this.payMoney =
                Number(this.data.sumMoney) -
                Number(this.cusMoney.flhxMoney) -
                Number(this.cusMoney.cxhxMoney) -
                Number(this.data.disMoney);
            console.log(this.payMoney, "计算金额y");

            this.payMoney = util.toFixed2(this.payMoney);
        },
        selectConfirm() {
            let ccuscode = this.model.code
                ? this.model.code
                : this.vuex_basCus.code;
            this.$u.api.shop.addressListData({ ccuscode }).then((res) => {
                if (res.list.length) {
                    this.addressData = res.list[0];
                } else {
                    this.addressData = {};
                }
            });
        },
        replaceInput(e) {
            console.log(e);
            var that = this;
            e = e.match(/^\d*(\.?\d{0,2})/g)[0];
            this.$nextTick(() => {
                that.value = e;
            });
        },
        submit() {
            if (
                (this.curCus.bmn == "1" && !this.model.code) ||
                (this.curCus.bsjmn == "1" && !this.model.code)
            ) {
                this.$u.toast("请选择核发门店");
                return;
            } else if (
                !this.addressData.cdeliverunit ||
                !this.addressData.cdeliveradd
            ) {
                this.$u.toast("请先完善收货信息");
                return;
            }

            // 如果是首批用户，直接提交订单，不选择赠品
            if (this.vuex_basCus.batchType == "1") {
                console.log("首批用户，直接提交订单，不选择赠品");
                this.proceedWithOrder([]);
                return;
            }

            // 非首批用户，检查赠品
            this.checkGiftAndSubmit();
        },

        // 检查赠品并提交订单
        checkGiftAndSubmit() {
            const cusCode = this.vuex_basCus ? this.vuex_basCus.code : "";

            if (!cusCode) {
                uni.showToast({
                    title: "客户信息不完整",
                    icon: "none",
                });
                return;
            }

            // 调用赠品API检查是否有可用赠品
            this.$u.api.shop
                .shopGiftListData({ cusCode })
                .then((res) => {
                    console.log("赠品检查结果:", res);

                    if (res.list && res.list.length > 0) {
                        // 有赠品，显示赠品选择弹窗
                        this.cusCode = cusCode;
                        this.payGiftMoney = this.payMoney;
                        this.showGiftModal = true;
                    } else {
                        // 没有赠品，直接提交订单
                        this.proceedWithOrder([]);
                    }
                })
                .catch((error) => {
                    console.error("获取赠品数据失败:", error);
                    // 获取赠品失败，直接提交订单
                    this.proceedWithOrder([]);
                });
        },

        // 继续提交订单
        proceedWithOrder(selectedGifts = []) {
            console.log("提交订单，包含赠品:", selectedGifts);

            // 这里添加原来的订单提交逻辑
            if (
                (this.curCus.bmn == "1" && !this.model.code) ||
                (this.curCus.bsjmn == "1" && !this.model.code)
            ) {
                this.$u.toast("请选择核发门店");
            } else if (
                !this.addressData.cdeliverunit ||
                !this.addressData.cdeliveradd
            ) {
                this.$u.toast("请先完善收货信息");
            } else {
                let params = {
                    hfmdCode: this.model.code ? this.model.code : "",
                    cusCode: this.vuex_basCus.code,
                    cusMoney: this.data.cusMoney,
                    disMoney: this.data.disMoney,
                    zhMoney: this.payMoney,
                    flMoney: this.cusMoney.flhxMoney,
                    cxMoney: this.cusMoney.cxhxMoney,
                    sumMoney: this.data.sumMoney,
                    payMoney: this.payMoney,
                    selIds: this.data.carList.map((item) => item.id).join(","),
                    carList: this.data.carList,
                    zpList: selectedGifts, // 添加选中的赠品
                    remarks: this.remarks,
                    person: this.addressData.cdeliverunit,
                    phone: this.addressData.cenglishadd4,
                    address: this.addressData.cdeliveradd,
                };
                console.log(params);
                this.$u.api.shop.saveOrderFromShopCar(params).then((res) => {
                    if (res.result == "true") {
                        this.$u.toast(res.message);
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1,
                            });
                        }, 500);
                        // 此处添加 逻辑如果首批用户下首批订单成功以后
                        // vuex_basCus vuex_basCus.batchType 为 1 ,更新 vuex_basCus vuex_basCus.batchType 为 2, batchPages 为 ''
                        // 并且this.data.carList  里面carList 数组里面的 shopSalesPackage.title 一致
                        // 才更新 vuex_basCus vuex_basCus.batchType 为 2, batchPages 为 ''
                        if (this.vuex_basCus.batchType == 1) {
                            let titles = this.data.carList.map(
                                (item) => item.shopSalesPackage.title
                            );
                            if (
                                titles.every(
                                    (title) =>
                                        title == this.vuex_basCus.batchPages
                                )
                            ) {
                                // this.$store.commit("modifyBasCus",this.vuex_basCus)
                                this.$u.vuex("vuex_basCus", {
                                    code: this.vuex_basCus.code,
                                    name: this.vuex_basCus.name,
                                    batchPages: "",
                                    batchType: 2,
                                });
                            }
                        }
                    } else {
                        uni.showModal({
                            title: "提示",
                            content: res.message,
                            showCancel: false,
                            success: function (res) {},
                        });
                    }
                });
            }

            // 临时提示，实际应该调用订单提交API
            // uni.showToast({
            // 	title: `订单提交成功，包含${selectedGifts.length}个赠品`,
            // 	icon: 'success'
            // });
        },
        // address(){
        // 	uni.navigateTo({
        // 		url: '/pages/btdm/index/user/address/index',
        // 	})
        // },
        modify(flag) {
            this.focus = false;
            this.numShow = true;
            this.flag = flag;
            // 同时设置promotionType以保持一致性
            this.promotionType = flag;
            if (flag == 1) {
                this.value =
                    this.cusMoney.flhxMoney != "0.00"
                        ? this.cusMoney.flhxMoney
                        : "";
            } else if (flag == 2) {
                this.value =
                    this.cusMoney.cxhxMoney != "0.00"
                        ? this.cusMoney.cxhxMoney
                        : "";
            }
            setTimeout(() => {
                this.focus = true;
            }, 500);
        },
        modifyAllocation() {
            if (!this.isRatio) {
                return uni.showToast({
                    title: "没有分类商品",
                    icon: "none",
                });
            }
            this.promotionType = 2;
            this.showAllocationModal = true;
        },

        // addressData(address) {
        // 	this.title = address.site;
        // 	this.show = false
        // },
        xzAddress() {
            let ccuscode = this.model.code
                ? this.model.code
                : this.vuex_basCus.code;
            uni.navigateTo({
                url:
                    "/pagesData/pages/user/address/addSite?ccuscode=" +
                    ccuscode,
            });
        },
        toggleDetails(shopSalesPackage, index) {
            const packageId = shopSalesPackage.id;
            // 切换展开状态
            this.$set(
                this.expandedPackages,
                packageId,
                !this.expandedPackages[packageId]
            );

            // 如果是展开状态且还没有加载数据，则获取数据
            if (
                this.expandedPackages[packageId] &&
                !this.packageDetails[packageId]
            ) {
                console.log("展开套餐包详情:", shopSalesPackage, this.data);

                // 通过API获取套餐包的详细物料信息
                this.$u.api.shop
                    .shopSalesData({ id: this.data.selIds })
                    .then((res) => {
                        console.log("套餐包详细数据:", res);

                        // 保存套餐包详情数据
                        this.$set(this.packageDetails, packageId, {
                            wlList: res.shopSalesPackage.wlList || [],
                            mainList: res.shopSalesPackage.mainList || [],
                            fpList: res.shopSalesPackage.fpList || [],
                            czpList: res.shopSalesPackage.czpList || [],
                            title: "套餐包",
                        });
                        console.log("this.packageDetails", this.packageDetails);
                    })
                    .catch((error) => {
                        console.error("获取套餐包详情失败:", error);
                        uni.showToast({
                            title: "获取详情失败",
                            icon: "none",
                        });
                        // 获取失败时关闭展开状态
                        this.$set(this.expandedPackages, packageId, false);
                    });
            }
        },
        // 组件事件处理方法
        onProductClick(item) {
            console.log("产品点击:", item);
        },
        onQuantityChange(data) {
            console.log("数量变化:", data);
        },
        onItemSelect(data) {
            console.log("选择状态变化:", data);
        },
        // 赠品弹窗事件处理
        onGiftCancel(Boolean) {
            if (!Boolean) {
                this.showGiftModal = false;
            } else {
                // 是否确认取消赠品
                uni.showModal({
                    title: "提示",
                    content: "确定取消选择赠品吗？",
                    success: (res) => {
                        if (res.confirm) {
                            this.showGiftModal = false;
                            // 取消赠品，直接提交订单
                            this.proceedWithOrder([]);
                        } else if (res.cancel) {
                            // 取消操作，保持当前状态
                            this.showGiftModal = false;
                        }
                    },
                });
            }
        },
        onGiftConfirm(selectedGifts) {
            // 如果没有选择赠品提示用户
            if (selectedGifts.length === 0) {
                uni.showToast({
                    title: "请选择赠品",
                    icon: "none",
                });
                return;
            }

            this.showGiftModal = false;
            // 确定带赠品，提交订单
            this.proceedWithOrder(selectedGifts);
        },
        confirm() {
            if (Number(this.value) < 0) {
                this.$u.toast("输入余额不能小于0");
                return false;
            }
            // 返利
            if (this.flag == 1) {
                // 由于现在是radio选择，不需要检查两者之和
                if (Number(this.value) <= Number(this.data.flMoneyLmit)) {
                    this.cusMoney.flhxMoney = util.toFixed2(this.value);
                    // 确保促销余额为0（因为选择了返利）
                    this.cusMoney.cxhxMoney = "0.00";
                    this.calculatePayMoney();
                } else {
                    uni.showModal({
                        title: "提示",
                        content: "不能超过返利金额上限",
                        showCancel: false,
                        success: function (res) {},
                    });
                    // this.$u.toast('不能超过返利金额上限');
                }

                // if ((Number(this.value) + Number(this.cusMoney.cxhxMoney)) > Number(this.data.sumMoneyLmit)) {
                // 	this.$u.toast('返利金额促销金额之和不能大于商品总价');
                // 	return false;
                // }

                // // Number(this.data.cusMoney.appFlMoney)
                // if (Number(this.value) <= Number(this.data.flMoneyLmit)) {
                // 	this.cusMoney.flhxMoney = util.toFixed2(this.value);
                // 	this.payMoney = Number(this.data.sumMoney) - Number(this.cusMoney.flhxMoney) - Number(this.cusMoney
                // 		.cxhxMoney) - Number(this.data.disMoney)

                // 	this.payMoney = util.toFixed2(this.payMoney)
                // } else {
                // 	this.$u.toast('不能超过返利金额上限');
                // }
            }
            // 促销
            if (this.flag == 2) {
                // 由于现在是radio选择，不需要检查两者之和
                if (Number(this.value) <= Number(this.data.cxMoneyLmit)) {
                    this.cusMoney.cxhxMoney = util.toFixed2(this.value);
                    // 确保返利余额为0（因为选择了促销）
                    this.cusMoney.flhxMoney = "0.00";
                    this.calculatePayMoney();
                } else {
                    uni.showModal({
                        title: "提示",
                        content: "不能超过促销金额上限",
                        showCancel: false,
                        success: function (res) {},
                    });
                    // this.$u.toast('不能超过促销金额上限');
                }

                // if ((Number(this.value) + Number(this.cusMoney.flhxMoney)) > Number(this.data.sumMoney)) {
                // 	this.$u.toast('返利金额促销金额之和不能大于商品总价');
                // 	return false;
                // }
                // // Number(this.data.cusMoney.appCxMoney)
                // if (Number(this.value) <= Number(this.data.cxMoneyLmit)) {
                // 	this.cusMoney.cxhxMoney = util.toFixed2(this.value)
                // 	this.payMoney = Number(this.data.sumMoney) - Number(this.cusMoney.flhxMoney) - Number(this.cusMoney
                // 		.cxhxMoney) - Number(this.data.disMoney)
                // 	this.payMoney = util.toFixed2(this.payMoney)
                // } else {
                // 	this.$u.toast('不能超过促销金额上限');
                // }
            }
        },
        onRatioConfirm(e, ratio) {
            console.log(e, ratio);
            let list = e;
            this.cusMoney.cxhxMoney = (
                (Number(this.data.sumMoneyLmit) * Number(ratio)) /
                100
            ).toFixed(2);
            console.log(this.cusMoney.cxhxMoney, "--------");

            list.forEach((item) => {
                if (item.busType == "0") {
                    item.shopInv.ratio = isNaN(item.ratio) ? 0 : item.ratio;
                }
                if (item.busType == "1") {
                    item.shopProductSell.ratio = isNaN(item.ratio)
                        ? 0
                        : item.ratio;
                }
                if (item.busType == "3") {
                    item.salesRefList.forEach((it) => {
                        it.ratio = isNaN(it.ratio) ? 0 : it.ratio;
                    });
                }
            });
            console.log(list, "-------");
            this.calculatePayMoney();
            this.$set(this.data, "carList", list);
        },
    },
};
</script>

<style lang="scss" scoped>
page {
    width: 100%;
    height: 98%;
    text-align: center;
    overflow: scroll;
}

.item-menu-image {
    width: 100px;
    height: 85px;
}

textarea {
    width: 100%;
    height: 260rpx;
    background-color: #f7f7f7;
    line-height: 60rpx;
    // margin: 40rpx auto;
    padding: 20rpx;
}
</style>
